<?php


namespace Beerus\Modules\BrandLevel\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brandRights\BrandLevelRightsLeaveInfo;
use Biz\model\brandRights\BrandLevelRightsLeaveInfo as mBrandLevelRightsLeaveInfo;
use Biz\pockets\constInterface\BrandLevel;
use Biz\service\brand\Brand as sBrand;
use Biz\service\BrandRights\BrandLevelSourceRightsService;
use Doraemon\model\Phone as PhoneModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use hhz\constant\basic\UserExtendPhoneScene;
use Illuminate\Http\Request;

class LevelRightsLeaveInfoController extends Controller
{
    const  PAGE_SIZE = 20;

    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->setJsScript());
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $where['ORDER'] = ['id' => 'DESC'];
        $list = mBrandLevelRightsLeaveInfo::dataSelect($where);
        unset($where['LIMIT']);
        $total = mBrandLevelRightsLeaveInfo::dataCount($where);
        $gridModel = new GridDataModel($list, $total, [
            'perPage' => $page_size,
        ]);
        $sourceRights = BrandLevelSourceRightsService::getLevelSourceRights();
        $sourceRightsArr = array_column($sourceRights, 'rights_title', 'source_rights_id');
        $brands = [];
        if ($total > 0) {
            $brandIds = array_column($list, 'brand_id');
            $brands = sBrand::getBrandsInfoByIds($brandIds);
        }
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $sourceRightsArr, $brands) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) use ($sourceRightsArr) {
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_id', '品牌ID')->placeholder('品牌ID');
                        $filter->equal('uid', 'UID')->placeholder('UID');
                        $filter->equal('phone', '手机号')->placeholder('手机号');
                    });

                    $filter->column(1 / 2, function ($filter) use ($sourceRightsArr) {
                        $filter->equal('source_rights_id', '权益名称')->select($sourceRightsArr);
                        $filter->equal('day', '留资日期')->date('Y-m-d');
                        $doneText = ['未操作', '已操作'];
                        $filter->equal('done', '操作状态')->select($doneText);;
                    });

                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                //$grid->disableActions();
                $grid->column('id', 'ID');
                $grid->column('brand_id', '品牌[ID]')->display(function ($brand_id) use ($brands) {
                    return $brands[$brand_id]['brand_name'] . "[$brand_id]";
                });
                $grid->column('uid', 'UID');
                $grid->column('level', '等级')->display(function ($level) {
                    return BrandLevel::BRAND_LEVELS[$level] ?? '';
                });
                $grid->column('source_rights_id', '权益名称')->display(function ($source_rights_id) use ($sourceRightsArr) {
                    return $sourceRightsArr[$source_rights_id] ?? '';
                });
                $grid->column('day', '留资日期');
                $grid->column('phone', '手机号')->display(function () {
                    return '<a class="btn btn-default view-phone" data-id="' . $this->id . '">' . $this->phone . '</a>';
                });
                $grid->column('operator_id', '操作员')->display(function ($operator_id) {
                    if (!$operator_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($operator_id)->name;
                    }
                });
                $grid->column('done', '操作状态')
                    ->using(['未操作', '已操作'], '')->label(
                        [
                            0 => 'default',
                            1 => 'success',
                        ]
                    );
                $grid->column('remark', '备注')->editable();
                $grid->column('addtime', '留资时间');
                $grid->column('done_time', '操作时间');

                $grid->setActionClass(Actions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    if ($actions->row->done == 0) {
                        $html_set = ' <a class="fa fa-tag op-done" data-id="' . $actions->row->id . '" href="javascript:void(0);" style="margin-right: 5px">
                                    <span class="glyphicon" aria-hidden="true">操作完成</span></a>';
                        $actions->append($html_set);
                    }
                });

            });

        $tab = new Tab();
        $tab->add('等级权益留资列表', $grid->render(), true);
        $content->row($tab);

        return $content
            ->header('等级权益留资列表')
            ->description(' ')
            ->breadcrumb(['text' => '等级权益留资列表', 'url' => '/BrandLevel/leave']);
    }

    private static function getCondition($request): array
    {
        $condition = [];
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        }
        if (isset($request['uid']) && !empty($request['uid'])) {
            $condition['uid'] = $request['uid'];
        }
        if (isset($request['phone']) && !empty($request['phone'])) {
            $condition['phone'] = $request['phone'];
        }
        if (isset($request['source_rights_id']) && !empty($request['source_rights_id'])) {
            $condition['source_rights_id'] = $request['source_rights_id'];
        }
        if (isset($request['day']) && !empty($request['day'])) {
            $condition['day'] = $request['day'];
        }
        if (isset($request['done']) && !empty($request['done'])) {
            $condition['done'] = $request['done'];
        }
        return $condition;
    }

    public function save(Request $request, $id)
    {
        $params = $request->all();
        $name = $params['name'] ?? null;
        $value = $params['value'];
        if (!$name) {
            return response()->json([
                'message' => '操作失败',
                'status' => false,
            ]);
        }
        $data = [
            $name => $value,
            'edittime' => date('Y-m-d H:i:s', time()),
        ];
        mBrandLevelRightsLeaveInfo::dataUpdate($data, ['id' => $id]);
        $success = [
            'message' => '操作成功',
            'status' => true,
        ];
        return response()->json($success);
    }

    public function done(Request $request, $id)
    {
        $params = $request->all();
        $done = $params['done'] ?? 0;
        $data = [
            'done' => $done,
            'operator_id' => Admin::user()->id,
            'done_time' => date('Y-m-d H:i:s', time()),
            'edittime' => date('Y-m-d H:i:s', time()),
        ];
        mBrandLevelRightsLeaveInfo::dataUpdate($data, ['id' => $id]);
        $success = [
            'message' => '操作成功',
            'status' => true,
        ];
        return response()->json($success);
    }

    public function getPhone(Request $request, $id, WorkContent $content)
    {
        $info = BrandLevelRightsLeaveInfo::dataSelectInfo(['id' => $id]);
        $phone = $info['phone_encrypt_id'] ? PhoneModel::getExtendPhone($info['phone_encrypt_id'], UserExtendPhoneScene::BRAND_RIGHTS_LEAVE_INFO_PHONE) : '';
        return $content->row($phone);
    }


    private function setJsScript()
    {
        return <<<SCRIPT

        $('.op-done').unbind('click').click(function(){
             var id= $(this).data('id');
             swal({
                title: "确认已操作完成？",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
            }).then(function(confirm){
                if(confirm.value){
                    $.ajax({
                        url: window.location.pathname + "/done/" + id,
                        type: "POST",
                        async:false,
                        data: {
                            done: 1,
                            _method: 'PUT'
                        },
                        success: function (data) {
                            if (data.status)
                                toastr.success(data.message);
                            else
                                toastr.warning(data.message);
                            setTimeout(function () {
                               $.pjax.reload('#pjax-container');
                            }, 1000);
                        },
                        complete:function(xhr,status) {
                            if (status == 'success')
                                _status = xhr.responseJSON.status;
                        }
                    });
                }
            });
        });
        
        $('.view-phone').unbind('click').click(function(){
            var id = $(this).data('id');
            layer.open({
                type: 2,
                title: '留资手机号',
                maxmin: true,
                shadeClose: true,
                area: ['200px', '150px'],
                content:'/admin/BrandLevel/leave/getPhone/'+id,
            });
        });

SCRIPT;

    }


}